package com.heima.admin.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.dto.*;
import com.heima.admin.entity.AdChannel;
import com.heima.admin.entity.AdSensitive;
import com.heima.admin.feign.ArticleFeign;
import com.heima.admin.feign.WeMediaFeign;
import com.heima.admin.repository.ArticleRepository;
import com.heima.admin.service.IAdChannelService;
import com.heima.admin.service.IAdSensitiveService;
import com.heima.admin.service.IAuditService;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.SensitiveWordUtil;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class IAuditServiceImpl implements IAuditService {

    @Autowired
    private WeMediaFeign weMediaFeign;

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private IAdSensitiveService iAdSensitiveService;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private IAdChannelService iAdChannelService;

    @Autowired
    private ArticleRepository articleRepository;

    @Override
    @GlobalTransactional
    public void auditById(Integer id) {
        //根绝Id查询文章
        ResponseResult<WmNews> wmNewsResponseResult = weMediaFeign.getById(id);
        if (!wmNewsResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())
                || wmNewsResponseResult.getData() == null) {
            return;
        }
        WmNews wmNews = wmNewsResponseResult.getData();

        if (wmNews.getStatus() == 4 || wmNews.getStatus() == 8){
            if (wmNews.getPublishTime().getTime()<System.currentTimeMillis()){
                saveArticle(wmNews);
            }
        }

        //状态为1，审核
        if (wmNews.getStatus() == 1) {
            Boolean result = checkBySensitive(wmNews);
            //阿里审核
            if (!result) {
                return;
            }
            Boolean textAli = checkText(wmNews);
            if (!textAli) {
                return;
            }
            //图片审核
            Boolean imageAli = checkImage(wmNews);
            if (!imageAli) {
                return;
            }
            //判断文章的状态和时间,如果大于当前时间，就改状态为8
            if (wmNews.getPublishTime().getTime() >= System.currentTimeMillis()) {
                wmNews.setStatus(8);
                weMediaFeign.updateById(wmNews);
            } else {
                //保存文章
                saveArticle(wmNews);
            }
        }
    }

    private void saveArticle(WmNews wmNews) {
        //保存文章
        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, dto);
        ResponseResult<WmUser> responseResult = weMediaFeign.findUserById(wmNews.getUserId());
        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            WmUser wmUser = responseResult.getData();
            dto.setAuthorId(wmUser.getApAuthorId());
            dto.setAuthorName(wmUser.getName());
        }
        AdChannel adChannel = iAdChannelService.getById(wmNews.getChannelId());
        if (adChannel != null) {
            dto.setChannelName(adChannel.getName());
        }
        dto.setLayout(wmNews.getType());
        dto.setFlag(0);
        dto.setCreatedTime(new Date());
        dto.setContent(wmNews.getContent());
        ResponseResult<Long> longResponseResult = articleFeign.saveOrUpdateArticle(dto);
        if (longResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            Long articleId = longResponseResult.getData();

            wmNews.setArticleId(articleId);
            wmNews.setStatus(9);
            weMediaFeign.updateById(wmNews);

            //ES索引
            ApArticleSearch apArticleSearch = new ApArticleSearch();
            apArticleSearch.setId(articleId);
            apArticleSearch.setTitle(wmNews.getTitle());
            apArticleSearch.setAuthorId(wmNews.getUserId());
            apArticleSearch.setLayout(wmNews.getType());
            apArticleSearch.setImages(wmNews.getImages());
            apArticleSearch.setPublishTime(wmNews.getPublishTime());
            articleRepository.save(apArticleSearch);
        }
    }

    private Boolean checkImage(WmNews wmNews) {
        List<String> image = (List<String>) getTextAndImageFromContent(wmNews).get("image");
        if (image.size() > 0) {
            try {
                Map map = greenImageScan.checkUrl(image);
                String suggestion = (String) map.get("suggestion");
                String label = (String) map.get("label");
                //判断是否合法
                if (suggestion.equals("pass")) {
                    return true;
                }
                if (suggestion.equals("block")) {
                    wmNews.setStatus(2);
                    wmNews.setReason(label);
                    weMediaFeign.updateById(wmNews);
                    return false;
                }
                if (suggestion.equals("review")) {
                    wmNews.setStatus(3);
                    wmNews.setReason(label);
                    weMediaFeign.updateById(wmNews);
                    return false;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    private Boolean checkText(WmNews wmNews) {
        Map<String, Object> textAndImageFromContent = getTextAndImageFromContent(wmNews);
        String content = wmNews.getTitle() + textAndImageFromContent.get("text");
        try {
            Map map = greenTextScan.greenTextScan(content);
            String suggestion = (String) map.get("suggestion");
            String label = (String) map.get("label");
            //判断是否合法
            if (suggestion.equals("pass")) {
                return true;
            }
            if (suggestion.equals("block")) {
                wmNews.setStatus(2);
                wmNews.setReason(label);
                weMediaFeign.updateById(wmNews);
                return false;
            }
            if (suggestion.equals("review")) {
                wmNews.setStatus(3);
                wmNews.setReason(label);
                weMediaFeign.updateById(wmNews);
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private Boolean checkBySensitive(WmNews wmNews) {
        //判断敏感词Map是不是空
        if (SensitiveWordUtil.dictionaryMap.size() <= 0) {
            LambdaQueryWrapper<AdSensitive> query = new LambdaQueryWrapper<>();
            query.select(AdSensitive::getSensitives);
            List<String> list = iAdSensitiveService.listObjs(query, x -> (String) x);
            SensitiveWordUtil.initMap(list);
        }
        //判断文章开头是否合法
        Map<String, Integer> map = SensitiveWordUtil.matchWords(wmNews.getTitle());

        if (map.size() > 0) {
            wmNews.setStatus(2);
            wmNews.setReason("敏感词不通过");
            weMediaFeign.updateById(wmNews);
            return false;
        }

        //判断文本内容
        Map<String, Object> contentMap = getTextAndImageFromContent(wmNews);
        String text = (String) contentMap.get("text");
        if (StringUtils.isNotEmpty(text)) {
            Map<String, Integer> textMap = SensitiveWordUtil.matchWords(text);
            if (textMap.size() > 0) {
                wmNews.setStatus(2);
                wmNews.setReason("敏感词不通过");
                weMediaFeign.updateById(wmNews);
                return false;
            }
        }
        return true;

    }

    private Map<String, Object> getTextAndImageFromContent(WmNews wmNews) {
        Map<String, Object> map = new HashMap<>();
        ArrayList<String> images = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        String content = wmNews.getContent();
        List<ContentDto> contentDtos = JSON.parseArray(content, ContentDto.class);
        for (ContentDto contentDto : contentDtos) {
            //将文本内容和图片放入map
            if (contentDto.getType().equals("text")) {
                sb.append(contentDto.getValue());
            }
            if (contentDto.getType().equals("image")) {
                images.add(contentDto.getValue());
            }
        }
        map.put("text", sb.toString());
        map.put("image", images);
        return map;
    }
}
